<template>
  <div class="login">
    <div class="login-main">
      <h2>用户登录</h2>
      <van-form>
        <van-field
          v-model="nickname"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '用户名或密码错误' }, {pattern:/^\w{6,}$/}]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" @click="login">
            登录
          </van-button>
        </div>
      </van-form>
      <div class="toRegister">
        <p>
          <router-link to="/register">没有账号？请注册</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Form, Toast } from 'vant'

Vue.use(Form)

export default {
  name: 'Login',
  data () {
    return {
      nickname: '',
      password: ''
    }
  },
  methods: {
    login () {
      if (this.nickname.trim() === '') {
        return
      }
      if (this.password.trim() === '') {
        return
      }
      if (
        !this.password.match(/^\w{6,}$/)
      ) {
        return
      }
      let userInfo = localStorage.users
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        let rel = false
        userInfo.map(item => {
          if (
            this.nickname === item.nickname &&
            this.password === item.password
          ) {
            rel = true
            Toast('登陆成功')
            setTimeout(() => {
              this.$router.push({
                path: '/mine'
              })
            }, 1000)
            document.cookie = this.nickname
          }
        })
        if (rel) {
          sessionStorage.nickname = this.nickname
          this.$router.push({
            path: '/message'
          })
        } else {
          this.$notify({
            message: '账户或密码输入有误 请重试！'
          })
        }
      }
    }
  }
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
}
html,
body,
.login {
  height: 100%;
}
.login {
  display: flex;
  flex-direction: column;
}
.login-main {
  flex: 1;
  padding: 200px 0;
  text-align: center;
  h2{
    line-height: 3;
    color: #1989fa;
  }
}
.toRegister {
  p {
    line-height: 2;
    color: blue;
    font-size: 12px;
  }
}
</style>
